<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<link rel="stylesheet" type="text/css" href="../../../Themes/default/easyui.css">
		<link rel="stylesheet" type="text/css" href="../../../Themes/icon.css">
		<link rel="stylesheet" type="text/css" href="../../../CSS/demo.css">
		<link rel="stylesheet" type="text/css" href="../../../CSS/common.css">
	</head>

	<body style="padding:0px;background-color: white">
		<div id="toolbar" class="receipts_toolbar_style">
		</div>
		<div>
			<form id="ff" action="#" method="post">
				<table cellpadding="5" class="displaytable" style="text-align: left;width: 80%;margin: 0 auto;">
					<tr>
						<td width="20%">
							<h id="star">* </h>用户组</td>
						<td width="30%">
							<input class="easyui-combobox" style="width: 100%;" type="text" id="input_CUSTOMER_TYPE" name="CUSTOMER_TYPE" data-options="disabled:true" />
						</td>
						<td width="20%">
							<h id="star">* </h>配送单位名称</td>
						<td width="30%">
							<input class="easyui-combobox" style="width: 100%" type="text" id="input_CUSTOMER_NAME" name="CUSTOMER_NAME" data-options="disabled:true" />
						</td>
					</tr>
					<tr>
						<td>
							<h id="star">* </h>网络订单编号</td>
						<td>
							<input class="easyui-textbox" style="width: 100%;" type="text" name="WEBORDER_ID" id="input_WEBORDER_ID" data-options="prompt:'由系统自动生成，不需填写',disabled:true,required:'true'"></input>
						</td>
						<td>
							<h id="star">* </h>配送时间</td>
						<td>
							<input class="easyui-datebox" style="width:100%;" type="text" name="DISTRIBUTION_DATE" id="input_DISTRIBUTION_DATE" data-options="prompt:'由系统自动生成，不需填写',disabled:true,required:'true'" />
						</td>
					</tr>
				</table>
				<table id="tt">

				</table>

				<div style="padding: 10px 0px;">
					<table>
						<tr>
							<th>人民币金额合计</th>
							<td>
								<input type="text" style="border: none;" name="number" />
							</td>
							<th>人民币金额合计(大写)</th>
							<td width="auto">
								<input type="text" style="border: none; width: 500px;" id="dx" />
								<!--<div id="dx"></div>-->
							</td>
						</tr>
					</table>
				</div>
				<div style="margin-left: 20%;" id="new_footer">

				</div>
			</form>
		</div>
		<div id="dlg" class="hiddenDialog">
			<iframe id="ifrmEdit" style="width: 100%;height: 100%;" frameborder="0" scrolling="no"></iframe>
		</div>
	</body>
	<script type="text/javascript" src="../../../JS/jquery.min.js"></script>
	<script type="text/javascript" src="../../../JS/jquery.easyui.min.js"></script>
	<script type="text/javascript" src="../../../JS/common.js"></script>
	<script type="text/javascript" src="../../../JS/finance.js"></script>
	<script type="text/javascript" src="../../../JS/jquery.edatagrid.js"></script>
	<script type="text/javascript" src="../../../JS/SHA-1.js"></script>
	<script type="text/javascript">
		var _thiscity; //保存当前页面的city
		var searchCode = undefined;
		var id; //获取上个页面传回的ID,
		var currPage = 0; //当前的页数
		var currid;
		var MaxPage = 0;
		var MinPage = 1;
		var WebData = [];
		var convertData = new Array();
		var currRow;
		var storageData = new Object(); //保存localstorage里的数据
		var localAdre = "webdata"; //localstorage存放数据的地址
		var _detailToolbarData;
		var receiptType; //单据的功能按钮类型
		_detailToolbarData = AddDetailToolBar(2);
		addFooter($("#new_footer"));
		var tooldata = [{
			"icon": "icon-save",
			"func": "save()",
			"functionname": "保存转换表"
		},{
			"icon": "icon-to_do",
			"func": "getWebData()",
			"functionname": "获取网络订单"
		}, {
			"icon": "icon-to_do",
			"func": "clearWebData()",
			"functionname": "清空网络订单"
		}]; //tooldata为新增的toolbar数据
		//增加单据的toolbar
		receiptType = RECEIPT_FRONT_SYMBOL + RECEIPT_NEXT_SYMBOL;
		receiptType +=  RECEIPT_SEARCH_SYMBOL + RECEIPT_VERIFY_SYMBOL;
		content = AddReceiptsToolBar(receiptType, tooldata);
		$("#toolbar").append(content); /*在ID=toolbar的标记后面添加content中的内容*/
		$(document).ready(function() {
			var returnData;
			if((returnData = getMultiID()) != undefined) {
				id = returnData.id;
				searchCode = returnData.city;
				currid = id;
			}
			getAllData();
			GetDetailTable();
			getRemoteData(currPage);
		});

		function getWebData() //获取网络数据
		{
			var pLocation = 'UI/LOGISTICS/WebOrder/WebOrderDataGet.html';
			$('#ifrmEdit').attr('src', pLocation);
			constructDialog($("#dlg"), "新增", 300, 340);
			AddDialog.dialog('open');
		}

		function clearWebData() {
			$.messager.confirm('Confirm', '是否清空网络数据缓存', function(r) {
				if(r) {
					localStorage.setItem(localAdre, "");
					$.messager.alert("提示", "清空成功");
				}
			});

		}

		$('#input_CUSTOMER_NAME').combobox({ //选中id为customer_name的combobox
			onSelect: function(record) { //当选中数据后调用该function，并得到该combobox对应的valuefield和textfield，赋值给record
					$('#input_customer_id').textbox('setValue', record.CUSTOMER_ID);
				} //调用easyui的textbox的写入值方法，将record中name为CUSTOMER_ID的写入id为customer_id的textbox中
		});
		
		function frontpage() {
			if(currPage > MinPage) {
				currPage = currPage - 1
				getRemoteData(currPage);
			} else {
				$.messager.alert("提示", "没有上张");
			}
		}

		function nextpage() {
			if(currPage < MaxPage) {
				currPage = currPage + 1;
				getRemoteData(currPage);
			} else {
				$.messager.alert(" 提示", "没有下张");
			}

		}

		function searchmore() {
			AddTabIn("网络订单查询", parent.$('#tabs'), "UI/LOGISTICS/WebOrder/WebOrderSearch.html?id=" + currPage);
		}
		
		
		//获取localstorage里的数据
		function getLocalstorage() {
			var _localData = null;
			_localData = localStorage.getItem(localAdre);
			if(_localData != null && _localData != "" && _localData != undefined) {
				storageData = JSON.parse(_localData);
				return storageData;
			} else {
				console.log("localStorage没有数据!");
				return null;

			}

		}

		function getAllData() {
			var WebDataObject = {};
			WebDataObject = getLocalstorage(); // 不能放到if语句中
			if(searchCode != undefined) {
				var parentLocation;
				parentLocation = searchParent("WebOrderSearch.html");
				WebData = parentLocation.returnSearchData();
				for(var i = 0 ,len = WebData.length ; i < len ; i++){
					if(WebData[i].city === searchCode && WebData[i].ID == currid){
						currPage = i;
						break;
					}
				}
			} else {
				var _localData;
				for(var s in WebDataObject) {
					WebData = WebData.concat(WebDataObject[s].rows);
				}
				currPage = 0;
			}
			MaxPage = WebData.length - 1;
			MinPage = 0;
		}

		function getRemoteData(pageNum) //统一获取远程的数据
		{
			if(pageNum > MaxPage) {
				pageNum = pageNum - 1;
			}
			var result = WebData[pageNum];
			if(typeof(result) != "undefined") {
				getFormData(result);
				currPage = pageNum;
				currid = result.ID;
				_thiscity = result.city;
				var _data = result.rows; //将获取到的数据中字头为rows的数据赋值给_data
				$('#tt').edatagrid('loadData', _data); //调用easyui的loadData方法，将数据写入id为tt的datagrid中
				CalSum();
				//判断审核状态
			}
		}
		var currIntertradeID = "";

		function GetDetailTable() { //构造datagrid中的数据
			$('#tt').edatagrid({
				height: 310,
				toolbar: _detailToolbarData, //toolbar选择自定义的名为toolbar的工具栏
				collapsible: 'true', //是否折叠：是
				singleSelect: 'true', //是否单选：是
				rownumbers: 'true',
				fitColumns: 'true', //自动调整列：是
				showFooter: 'true',
				autoSave: 'ture',
				columns: [
					[{
						field: 'INTERNALTRADE_ID',
						title: '内部商品ID',
						width: '8%',
						align: 'center',
						editor: {
							type: 'textbox',
							options: {
								valueField: "INTERNALTRADE_ID",
								textField: "INTERNALTRADE_ID",
								editable: false,
								required: true
							}
						}
					}, {
						field: 'INTERNAL_NAME',
						title: '*内部商品名',
						width: '13%',
						align: 'center',
						editor: {
							type: 'combobox',
							options: {
								valueField: 'INTERNAL_NAME',
								textField: 'INTERNAL_NAME',
								panelWidth: 200,
								panelHeight: 'auto',
								mode: 'remote',
								required: true,
								method: 'get',
								onChange: function(newValue, oldValue) {
									if(!isEnglish(newValue)) {
										return;
									}
									if(newValue != "" && newValue != undefined) {
										var url = RemoteLinkAddress + "/logistics/internaltrade/findbypinyin?PINYINFIELDNAME=" + newValue.trim();
										$(this).combobox("reload", url);
									}
								},
								onSelect: function(record) {
									var rowIndex = $("#tt").edatagrid('getRowIndex', currRow);
									var targeted = $('#tt').edatagrid('getEditor', {
										'index': rowIndex,
										'field': 'INTERNAL_TYPE'
									}).target;
									targeted.textbox('clear');
									targeted.textbox('setValue', record.INTERNAL_TYPE);
									var target = $('#tt').datagrid('getEditor', {
										'index': rowIndex,
										'field': 'INTERNALTRADE_ID'
									}).target;
									target.textbox('clear');
									if(record.ID != undefined) {
										target.textbox('setValue', record.ID);
									}
								}
							}
						},
					}, {
						field: 'INTERNAL_TYPE',
						title: '*内部商品类型',
						width: '13%',
						align: 'center',
						editor: {
							type: 'textbox',
							options: {
								valueField: "INTERNAL_TYPE",
								textField: "INTERNAL_TYPE",
								editable: true,
								required: true
							}
						}
					}, {
						field: 'TRADE_NAME',
						title: '*原始名称',
						width: '13%',
						align: 'center',
						id: 'trade_name',
					}, {
						field: 'UNIT_NAME',
						title: '*单位',
						width: '13%',
						align: 'center',
						editor: {
							type: 'textbox',
							options: {
								valueField: "UNIT_NAME",
								textField: "UNIT_NAME",
							}

						}
					}, {
						field: 'AMOUNT',
						title: '*数量',
						width: '13%',
						align: 'center',
					}, {
						field: 'UNIT_PRICE',
						title: '*单价',
						width: '13%',
						align: 'center',
						editor: {
							type: 'numberbox',
							options: {
								precision: 2, //保留两位
								groupSeparator: ',', //每组用','隔开
								decimalSeparator: '.',
								prefix: '￥', //在数据前面加￥符号
								editable: false
							}

						},
						formatter: function(value, row, index) {
							if(value) {
								return "￥" + value;
							}
						}
					}, {
						field: 'SUM',
						title: '*总价',
						width: '13%',
						align: 'center',
						formatter: function(value, row, index) {
							if(value) {
								return "￥" + value;
							}
						}
					}]
				],
				onEndEdit: function(index, row, changes) { //在编辑完成或，执行该函数
					if(currIntertradeID != row.INTERNALTRADE_ID) { //只有id发生改变之后才允许推送到转换表数组中
						var data = Object();
						if(WebData[currPage].CUSTOMERTYPE_ID != "") {
							var checkConvertDataRes = checkConvertData(row, WebData[currPage].CUSTOMERTYPE_ID); //检查数组中是否存在该原始名称，如果有，则替换并返回false，如果无，则返回true
							if(!checkConvertDataRes) {
								return;
							}
							data.CUSTOMERTYPE_ID = WebData[currPage].CUSTOMERTYPE_ID;
							data.INTERNALTRADE_ID = row.INTERNALTRADE_ID;
							data.ORIGINAL_UNIT = row.UNIT_NAME;
							data.ORIGINAL_NAME = row.TRADE_NAME;
							convertData.push(data);
						} else {
							$.messager.alert("错误", "用户组不能为空");
							return;
						}
					}
				},
				onDblClickRow: function(index, row) {
					currIntertradeID = row.INTERNALTRADE_ID;
					currRow = row;
				},
				onClickRow: function(index, row) {
					currRow = row;
				}
			});
		}

		function verifydata() {
			$.messager.confirm('Confirm', '是否审核', function(r) {
				if(r) {
					var localPageData = WebData[currPage];
					var data = $('#tt').edatagrid('getRows');
					//对单据数据进行判断，提示用户能不能提交
					if(!(isTrueData(data))) {
						$.messager.alert("警告", "数据填写不完整！");
						return;
					}
					localPageData.rows = data;
					//获取input中的数据
					getInputData(localPageData);
					submitData(localPageData);
				} else {
					$.messager.alert("提示", "审核不成功!");
				}
			});
		}

		function submitData(_data) {
			var _url = "";
			_data.ISWEB = "0";
			_url = RemoteLinkAddress + "/logistics/originalorder/save.do";
			var _senddata = JSON.stringify(_data);
			$.ajax({
				dataType: 'JSON',
				url: _url,
				data: 'a=' + _senddata,
				type: "POST",
				success: function(result) {
					var revData = result.msg.split(";");
					if(revData[0] === 'success') {
						$.messager.alert("提示", "保存成功");
					}
					MaxPage--; //保存成功后，删除当前单据，单据总量少一
					deleteCurrData(currid , _thiscity);
					writeLocalstorage(storageData);
					currPage -- ;
					nextpage();
				},
				error: function(result) {
					$.messager.alert("错误", "保存不成功");
				}
			});
		}

		function CalSum() {
			var _num = 0;
			var dataGridRows = $("#tt").datagrid("getRows");
			for(var i = 0; i < dataGridRows.length; i++) {
				_num += dataGridRows[i].SUM;
			}
			_num = _num.toFixed(2); //四舍五入
			var num = changeMoneyToChinese(_num);
			$("#dx").val(num);
			$("input[name='number']").val(_num);
		}

		function writeLocalstorage(data) {
			localStorage.setItem(localAdre, JSON.stringify(data));
		}
		
		//对单据数据进行判断;
		function isTrueData(data) {
			var _this;
			for(var i = 0; i < data.length; i++) {
				_this = data[i];
				for(var s in _this) {
					if(s == "INTERNAL_NAME" || s == "INTERNAL_TYPE") {
						if(_this[s] == "") {
							return false;
						}
					}
				}
			}
			return true;
		}
		//取出input框中的数据
		function getInputData(_data) {
			_data.CUSTOMER_NAME = $("#input_CUSTOMER_NAME").combobox("getValue").trim(); //配送单位名称
			_data.CUSTOMER_TYPE = $("#input_CUSTOMER_TYPE").combobox("getValue").trim(); //用户组
			_data.ID = $("#input_WEBORDER_ID").textbox("getValue").trim(); //网络订单编号
			var getdate = $("#input_DISTRIBUTION_DATE").datebox("getValue").trim(); //配送时间
			_data.DISTRIBUTION_DATE = getdate.replace(/-/g, "/");
			_data.MEMO = $("#input_MEMO").textbox("getValue").trim(); //备注
			_data.ID = currid; //保存ID；
			_data.city = _thiscity;
		}

		function WriteToConvertTable(_data) {
			var msg = "";
			var _url = RemoteLinkAddress + "/logistics/converttable/save.do";
			$.post(_url, _data,
				function(result) {
					if(result.msg == "success") {
						$.messager.alert("提示","添加成功");
					} else {
						msg = "<div>存在冲突，是否需要更新</div>";
						msg += "<div>'" + result.msg + "'</div>";
						$.messager.confirm('Confirm', msg, function(r) {
							if(r) {
								UpdateConvertTable(result.msg, _data.INTERNALTRADE_ID);
							}
						});
					}
				},
				'json');
		}

		function UpdateConvertTable(msg, updateID) {
			var _data = new Object();
			var s = msg.split(";");
			for(var i = 0; i < s.length; i++) {
				var m = s[i].split(":");
				_data[m[0]] = m[1];
			}
			_data.INTERNALTRADE_ID = updateID;
			var _url = RemoteLinkAddress + "/logistics/converttable/update.do";
			$.post(_url, _data,
				function(result) {
					if(result.msg.search("success") > -1) {
						$.messager.alert("提示", "更新成功");
					} else {
						$.messager.alert("提示", "更新失败");
					}
				},
				'json');
		}

		function exportExcel() {
			$.messager.confirm("提示", "确认导出Excel表格吗？", function(r) {
				if(r) {
					$.ajax({ //调用ajax方法，从服务器获取到该订单的所有数据
						type: "get",
						dataType: "json", //服务器返回的数据类型
						url: RemoteLinkAddress + "/logistics/converttable/excelorder.do",
						data: {
							"ID": currPage
						},
						success: function(result) {
							window.location.href = result.path;
						}, //请求成功后，接受服务器传来的Json字符串，并做相应的处理
						error: function(xhr, status, error) {
							$.messager.alert("错误", "请求失败!");
						}
					});
				}
			});
		}
		
		function save(){
			saveConverData();
		}
		
		function saveConverData(){
			for(var data of convertData) {
				WriteToConvertTable(data);
			}
			convertData = []; //保存之后清空数据库
		}
		
		function deleteCurrData(_id,_code){
			var s;
			for(var i = 0,len = WebData.length ; i<len ;i++){
				if(WebData[i].city === _code && WebData[i].ID == _id){
					WebData.splice(i, 1);
					break;
				}
			}
			var _data = storageData[_code].rows;
			for(var j = 0,lens = _data.length ; j<lens ;j++){
				if(_data[j].city === _code && _data[j].ID == _id){
					_data.splice(j, 1);
					break;
				}
			}
			storageData[_code].rows = _data;
		}

		function checkConvertData(row, customerTypeID) {
			if(convertData.length == 0) {
				convertData[0] = new Object();
				convertData[0].CUSTOMERTYPE_ID = customerTypeID;
				convertData[0].INTERNALTRADE_ID = row.INTERNALTRADE_ID;
				convertData[0].ORIGINAL_UNIT = row.UNIT_NAME;
				convertData[0].ORIGINAL_NAME = row.TRADE_NAME;
			}
			for(var singleConvertData of convertData) {
				if(singleConvertData.ORIGINAL_NAME == row.TRADE_NAME) {
					//找到了，此时应该替换
					singleConvertData.CUSTOMERTYPE_ID = customerTypeID;
					singleConvertData.INTERNALTRADE_ID = row.INTERNALTRADE_ID;
					singleConvertData.ORIGINAL_UNIT = row.UNIT_NAME;
					singleConvertData.ORIGINAL_NAME = row.TRADE_NAME;
					return false;
				}
			}
			return true;
		}
	</script>

</html>